import Common from "../Common";
import {bcComp, isEmpty} from "../common/Helpers";
import Profile from "./Profile";

const {ccclass, property} = cc._decorator;

@ccclass
export default class WithdrawDialog extends Common {


    @property(cc.Node)
    confirmBtn: cc.Node;

    @property(cc.Label)
    amountLabel: cc.Label;

    @property(cc.Label)
    descLabel: cc.Label;

    @property(cc.ToggleContainer)
    typeToggle: cc.ToggleContainer;


    protected formData: any = {
        money: '',
        password2: '',
        withdraw_type: '',
        withdraw_account: '',
    }
    protected watch = {
        userInfo: (val) => {
            const account = val.account || {}
            this.amountLabel.string = account.cash_account || 0.00
            this.descLabel.string = `注：最小提现金额：${val.min_withdraw || 0.01} 元，提现金额必须为 ${val.mul_withdraw || 0.01} 的倍数`;
        }
    }

    start() {
        this.confirmBtn.on(cc.Node.EventType.TOUCH_START, this.onWithdraw, this)
        this.formData.withdraw_type = 'weixin'
        this.checkToggle(this.formData.withdraw_type)
    }

    /**
     * 单选框选中
     * @param option
     * @param key
     */
    onToggleChange(option: cc.Toggle, key: string) {
        this.formData[key] = option.node.name
    }

    async onWithdraw() {
        this.onBtnClick()
        const formData = this.formData;
        if (bcComp(formData.money, 0) < 1) {
            return this.showToast('请输入合法的提现金额')
        }
        if (['weixin', 'alipay', 'bank'].indexOf(formData.withdraw_type) === -1) {
            return this.showToast('不支持该提款类型')
        }
        if (isEmpty(formData.withdraw_account)) {
            return this.showToast('请输入提款账号')
        }
        if (isEmpty(formData.password2)) {
            return this.showToast('请输入支付密码')
        }
        try {
            const {message} = await this.http.post('withdraw/withdraw', formData)
            this.showToast(message);
            this.node.active = false
            const userInfo = await this.node.parent.getComponent(Profile).initUserInfo(true)
            if (userInfo) {
                this._data.userInfo = userInfo
            }
        } catch ({message}) {
            this.showToast(message);
        }
    }

    checkToggle(name: string) {
        const children: cc.Node[] = this.typeToggle.node.children
        for (let item of children) {
            if (item.name === name) {
                item.getComponent(cc.Toggle).isChecked = true
                break;
            }
        }
    }
}
